package com.project.lk.nurseapp.common.view.bluetooth;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.project.lk.nurseapp.R;
import com.project.lk.nurseapp.base.BaseActivity;
import com.project.lk.nurseapp.utils.AppManager;
import com.project.lk.nurseapp.utils.XViewSettingUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 功能介绍：
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */

public class BluetoothListActivity extends BaseActivity {


    @BindView(R.id.xrecyclerview)
    XRecyclerView xrecyclerview;
    private BluetoothItemAdapter adapter;
    private Intent intentService;


    List<BlueTooth> mList=new ArrayList<>();
    private BluetoothAdapter mBluetoothAdapter;
    BleManager bleManager;

    @SuppressLint("NewApi")
    @Override
    protected void initData() {
        startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 1);
    }


    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        bleManager = BleManager.init();
        bleManager.initialize();
        //获取本地蓝牙适配器
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter =bluetoothManager .getAdapter();  //取得系统蓝牙模块适配器
        scanLeDevice(true); //扫描蓝牙
        adapter = new BluetoothItemAdapter(mList,this);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        XViewSettingUtils.setting(xrecyclerview,adapter,manager);
        xrecyclerview.setPullRefreshEnabled(false);
        xrecyclerview.setLoadingMoreEnabled(false);
        adapter.setOnItemEvent(new BluetoothItemAdapter.ItemEventListenter() {  //条目点击事件
            @Override
            public void conntItem(int position) {
//                mBinder.getService().disconnect();
                if (mScanning) {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    mScanning = false;
                }
                Log.e("MLOG",position+">>>>>>>>"+adapter.getList().get(position).getAddress());
              startActivity(new Intent(BluetoothListActivity.this,BluetoothDetailsActivity.class)
              .putExtra("BlueTooth",adapter.getList().get(position)));

           // bleManager.connect(adapter.getList().get(position).getAddress());

            }
        });

    }





    boolean mScanning=true;
   long  SCAN_PERIOD=2000; //延迟时间
    @Override
    protected int getLayoutId() {
        return R.layout.activity_bluetooth_list;
    }
    // 扫描设备
    @SuppressLint("NewApi")
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            Log.e("MLOG", "1 step start ScanLedevice");
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @SuppressLint("NewApi")
                @Override
                public void run() {
                     if (mScanning) {
                     mScanning = false;
                     mBluetoothAdapter.stopLeScan(mLeScanCallback);//停止扫描
                     invalidateOptionsMenu();
                     }
                }
            },SCAN_PERIOD);

            mScanning = true;
            liDevices.clear();
            mHandler.sendEmptyMessage(0);
            mBluetoothAdapter.startLeScan(mLeScanCallback);//开始扫描设备
        } else {
            Log.e("MLOG", "stop  Sacan device");
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }

    }
    //蓝牙设备
  private List<BluetoothDevice> liDevices = new ArrayList<BluetoothDevice>();

    // 扫描蓝牙设备的回调
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi,
                             final byte[] scanRecord) {
            Log.e("MLOG",rssi+">>>>");
            runOnUiThread(new Runnable() {
                @SuppressLint("NewApi")
                @Override
                public void run() {
                    Log.e("MLOG", "add device");
                    liDevices.add(device);
//                    Log.e("MLOG",device.getName());
                    BlueTooth model = new BlueTooth();
                    model.setAddress(device.getAddress());
                    model.setName(device.getName());
                    model.setType(device.getType());
                    model.setUuid(device.getUuids());
                    mList.add(model);
                    if(adapter != null) {
                    }
                    adapter.setmList(mList);

                    adapter.notifyDataSetChanged();
                }
            });
        }
    };

//通过handle取出扫描结果并进行其他操作，我这这里是判断扫描结果中是否有上次链接的缓存记录，如果有进行自动重连
    @SuppressLint("HandlerLeak")
    public final Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: // Notify change
                //!CoushionApplication.isconnect &&
                    if (liDevices.size() > 0) {// 如果没有连接，并且已经扫描到蓝牙设备
                        SharedPreferences mySharedPreferences = getSharedPreferences(
                                "device", Activity.MODE_PRIVATE);
                        String address = mySharedPreferences.getString(
                                "DeviceAddress", "");// 获取上次链接的设备地址
                        if (!address.equals("")) {
                            for (int i = 0; i < liDevices.size(); i++) {
                                if (liDevices.get(i).getAddress().equals(address)) {
                                    bleManager.connect(address);
                            //BluetoothLeService.connect(address);//根据地址链接蓝牙设备
                                    break;
                                }
                            }
                        }
                    }

                    break;
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    @SuppressLint("NewApi")
    @OnClick({R.id.back, R.id.refresh_but})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.refresh_but:
                scanLeDevice(true); //重新扫描蓝牙
                break;

        }
    }




}
